﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

//https://www.youtube.com/watch?v=xgLRe7QV6QI

namespace Game
{
    class Program
    {
        private static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static List<Socket> clients = new List<Socket>();
        private static List<string> ids = new List<string>();
        private static List<string> pos = new List<string>();
        private static List<string> posbolax = new List<string>();
        private static List<string> posbolay = new List<string>();

        private static byte[] buffer = new byte[1024];

        static void Main(string[] args)
        {
            Console.Title = "Server";
            SetUp();
            Console.ReadLine();
        }

        private static void SetUp()
        {
            Console.WriteLine("Iniciando Servidor...");
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
            serverSocket.Listen(5);
            serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
        }

        private static void AcceptCallBack(IAsyncResult ar)
        {
            Socket socket = serverSocket.EndAccept(ar);
            clients.Add(socket);
            Console.WriteLine("Cliente conectado");
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
            serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
        }

        private static void ReceiveCallBack(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            int received = socket.EndReceive(ar);
            byte[] dataBuffer = new byte[received];
            Array.Copy(buffer, dataBuffer, received);

            string text = Encoding.ASCII.GetString(dataBuffer);
            //Console.WriteLine(text);

            string response = string.Empty;
            char[] separador = { '|' };
            string[] textoSplit = text.Split(separador, StringSplitOptions.RemoveEmptyEntries);

            if (textoSplit[0] == "ID")
            {
                ids.Add(textoSplit[1]);
                pos.Add("0");
                Console.WriteLine(textoSplit[1]);

              //  Console.WriteLine(clients.Count.ToString());

                if (clients.Count == 2)
                    response += "Iniciar$";
            }
            else
            {
                for (int i = 0; i < ids.Count; i++)
                {
                    if (ids[i] == textoSplit[0])
                    {
                        pos[i] = textoSplit[1];
                        posbolax[i] = textoSplit[2];
                        posbolay[i] = textoSplit[3];
                    }

                    response += ids[i] + "|" + pos[i] + "|" + posbolax[i] + "|" + posbolay[i] + "$";
                }
                Console.WriteLine(response); 
            }

            byte[] data = Encoding.ASCII.GetBytes(response);

            foreach (Socket s in clients)
            {
                s.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), s);
                s.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), s);
            }
        }

        private static void SendCallBack(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            socket.EndSend(ar);
        }
    }
}
